import React, { Component } from 'react';
import { Card, Button, Table, Modal } from 'antd';
import SaveForm from './save-form';
import { v4 as uuidv4 } from 'uuid';

let sourceData = [{
    "_id": {
      "$oid": "5e0d7292bd72914ee8e714d4"
    },
    "name": "测试",
    "auth_time": 1607481252131,
    "auth_name": "admin",
    "create_time": 1554639521749,
    "menus": [
      "/category",
      "/home"
    ]
  },{
    "_id": {
      "$oid": "5e171d55d59eb648d4ed66a8"
    },
    "menus": [
      "/home",
      "/products",
      "/category",
      "/product",
      "/charts/pie"
    ],
    "name": "测试",
    "create_time": 1578573141547,
    "auth_name": "admin",
    "auth_time": 1607406938634
  },{
    "_id": {
      "$oid": "5e175a134bce5e36d48fb4db"
    },
    "menus": [
      "all",
      "/home",
      "/products",
      "/category",
      "/product",
      "/user",
      "/role",
      "/charts",
      "/charts/bar",
      "/charts/line",
      "/charts/pie"
    ],
    "name": "管理员",
    "create_time": 1578588691768,
    "auth_name": "admin",
    "auth_time": 1578588698490
  },{
    "_id": {
      "$oid": "5e188bb874c89321209fedda"
    },
    "menus": [
      "/home",
      "/charts/bar",
      "/charts",
      "/charts/line",
      "/charts/pie",
      "/role"
    ],
    "name": "员工",
    "create_time": 1578666936202,
    "auth_name": "admin",
    "auth_time": 1607330722391
  },{
    "_id": {
      "$oid": "5fcdca798e518d46807aa484"
    },
    "menus": [
      "/category"
    ],
    "name": "你好",
    "create_time": 1607322233401,
    "auth_time": 1607411041057,
    "auth_name": "admin"
  },{
    "_id": {
      "$oid": "5fcdcb428e518d46807aa485"
    },
    "menus": [],
    "name": "哈哈哈",
    "create_time": 1607322434116
  },{
    "_id": {
      "$oid": "5fcdcb528e518d46807aa486"
    },
    "menus": [],
    "name": "哈哈啊",
    "create_time": 1607322450051
  },{
    "_id": {
      "$oid": "5fcdcd638e518d46807aa488"
    },
    "menus": [],
    "name": "123",
    "create_time": 1607322979807
  }].map(v => {
    return {
        ...v,
        '_id': v['_id']['$oid']
    }
  });

/**
 * 角色
 */
class Role extends Component {

    saveForm = React.createRef();

    state = {
        loading: false,
        roles: [],
        // 选中的role
        role:{},
        visible: false,
        modalTitle: ''
    };


    /**
     * 初始化列
     */
     initColumns = () => {
        this.columns = [
            {
              title: '角色名称',
              dataIndex: 'name',
            },
            {
               title: '创建时间',
               dataIndex: 'create_time',
            },
            {
               title: '授权时间',
               dataIndex: 'auth_time',
            },
            {
                title: '授权人',
                dataIndex: 'auth_name',
            }
        ];
    }

    /**
     * 获取角色列表数据
     */
    getRoles = () => {
        this.setState({ loading: true, roles: [] });
        setTimeout(() => {
            this.setState({
                loading: false,
                roles: [...sourceData]
            });
        }, 1000);
    }

    /**
     * 行事件
     */
    onRow = (row) => {
        return {
            // 单击事件
            onClick: event => {
                this.setState({
                    role: row
                });
            }
        }
    }

    
    /**
     * 提交保存角色
     */
    handleOk = () => {
      if(this.state.modalTitle === '创建角色'){
        // 这里validateFields()直接返回promise
        this.form.current.validateFields().then(values => {
          const { name } = values;
          sourceData.unshift({
            '_id': uuidv4(),
            name,
            'create_time': new Date().getTime()
          });
        });
      }else{
        // 设置权限
        const { role } = this.state;
        // 获取最新menus
        console.log('this.saveForm:',this.saveForm);
        const menus = this.saveForm.current.getMenus();
        role.menus = menus;
        role['auth_name'] = new Date().getTime();
        sourceData.forEach(v => {
          if(v['_id'] === role['_id']){
            v = {...role};
          }
        });
      }
      
      this.setState({visible:false},() => {
        this.form.current.resetFields();
      });
      this.getRoles();
    }
    

    UNSAFE_componentWillMount(){
        this.initColumns();
    }


    componentDidMount(){
        // 去获取角色数据
        this.getRoles();
    }

    
    render() { 
        const { loading, roles, role, visible, modalTitle } = this.state;
        const title = (
            <span>
                <Button 
                type="primary" 
                style={{marginRight: '5px'}} 
                onClick={() => this.setState({ modalTitle: '创建角色',visible:true})}
                >创建角色</Button>
                <Button 
                type="primary" 
                disabled={!role['_id']}
                onClick={() => this.setState({ modalTitle: '设置角色权限',visible:true})}
                >设置角色权限</Button>
            </span>
        );

        return (
            <Card title={title}>
               <Table 
                loading={loading}
                bordered
                rowKey="_id"
                dataSource={roles} 
                columns={this.columns} 
                // 选中 selectedRowKeys
                rowSelection={{
                  type: 'radio',
                  selectedRowKeys:[role['_id']],
                  // 选择radio时回调
                  onSelect: (role) => {
                    this.setState({ role });
                  }
                }}
                onRow={this.onRow}
                pagination={{ defaultPageSize: 5, showQuickJumper: true, }}
                />

              <Modal 
                title={modalTitle}
                visible={visible} 
                onOk={this.handleOk} 
                onCancel={() => this.setState({visible: false})}
                >
                  <SaveForm 
                  ref={this.saveForm}
                  type={modalTitle === '创建角色' ? 'addRole' : 'setPerms'}
                  role={role}
                  setForm={(form) => {this.form = form}}
                  />
                </Modal>
            </Card>
        );
    }
}
 
export default Role;